package ace.cmp.security.oauth2.resource.server.test.service.impl;

import ace.cmp.security.oauth2.resource.server.core.constant.Oauth2ResourceServerConstant;
import ace.cmp.security.oauth2.resource.server.test.service.MockTokenIntrospectService;
import java.util.*;
import java.util.stream.Collectors;
import org.mockito.Mockito;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;

/**
 * @author caspar
 * @date 2023/8/22 10:53
 */
public class MockTokenIntrospectServiceImpl implements MockTokenIntrospectService {
  private final OpaqueTokenIntrospector introspector;

  public MockTokenIntrospectServiceImpl(OpaqueTokenIntrospector introspector) {
    this.introspector = introspector;
  }

  @Override
  public void mockClient(String... authorities) {
    Map<String, Object> attributes = new HashMap<>();
    attributes.put("accountId", "");
    List<GrantedAuthority> grantedAuthorities =
        Arrays.asList(authorities).stream()
            .map(p -> new SimpleGrantedAuthority(p))
            .collect(Collectors.toList());
    DefaultOAuth2AuthenticatedPrincipal principalDto =
        new DefaultOAuth2AuthenticatedPrincipal(
            UUID.randomUUID().toString(), attributes, grantedAuthorities);

    Mockito.when(introspector.introspect(Mockito.anyString())).thenReturn(principalDto);
  }

  @Override
  public void mockClient() {
    this.mockClient(Oauth2ResourceServerConstant.SCOPE_INTERNAL_CLIENT);
  }
}
